'use strict';

module.exports = app => {
  const { STRING, INTEGER, TEXT, BOOLEAN } = app.Sequelize;

  const Category = app.model.define('category', {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
    name: {
      type: STRING(50),
      allowNull: false,
      comment: '分类名称',
    },
    name_en: {
      type: STRING(50),
      allowNull: true,
      comment: '英文名称',
    },
    parent_id: {
      type: INTEGER,
      allowNull: true,
      comment: '父分类ID',
    },
    level: {
      type: INTEGER,
      defaultValue: 1,
      comment: '分类层级',
    },
    sort_order: {
      type: INTEGER,
      defaultValue: 0,
      comment: '排序',
    },
    icon: {
      type: STRING(255),
      allowNull: true,
      comment: '分类图标',
    },
    description: {
      type: TEXT,
      allowNull: true,
      comment: '分类描述',
    },
    is_active: {
      type: BOOLEAN,
      defaultValue: true,
      comment: '是否启用',
    },
    // 时间戳字段由Sequelize自动管理
  }, {
    tableName: 'categories',
    comment: '衣服分类表',
    indexes: [
      {
        fields: ['parent_id'],
      },
      {
        fields: ['level'],
      },
      {
        fields: ['sort_order'],
      },
    ],
  });

  Category.associate = function() {
    // 分类可以有多个子分类
    app.model.Category.hasMany(app.model.Category, {
      foreignKey: 'parent_id',
      as: 'children',
    });

    // 分类属于父分类
    app.model.Category.belongsTo(app.model.Category, {
      foreignKey: 'parent_id',
      as: 'parent',
    });

    // 分类下有多个衣服
    app.model.Category.hasMany(app.model.Clothing, {
      foreignKey: 'category_id',
      as: 'clothes',
    });
  };

  return Category;
};
